package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.SysRole;
import com.byit.domain.SysRoleMeun;
import com.byit.domain.SysUserRole;
import com.byit.enums.PromptInfo;
import com.byit.msg.MessageResult;
import com.byit.service.ISysRoleMeunService;
import com.byit.service.ISysRoleService;
import com.byit.service.ISysUserRoleService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author wangx
 * @since 2018-12-11
 */
@RestController
@RequestMapping("/api/sys/sysRole")
public class SysRoleController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysRoleMeunService roleMeunService;

    @Autowired
    private ISysUserRoleService userRoleService;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor dateEditor = new CustomDateEditor(format, true);
        binder.registerCustomEditor(Date.class, dateEditor);
    }

    @PostMapping("/save")
    public Object insertRole(HttpSession session, SysRole role) {
        Long userId = SessionHelper.getUserId(session);
        Long companyId = SessionHelper.getCompanyId(session);

        try {
            if (null == role) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }

            if (roleService.selectRoleByCode(role.getRoleCode())) {
                return MessageResult.warpper(PromptInfo.ROLE_IS_EXISTS);
            }

            role.setCreateTime(new Date());
            role.setOperationId(userId);
            if (null == role.getCompanyId()) {
                role.setCompanyId(companyId);
            }
            roleService.insertOrUpdate(role);

            if (!StringUtil.isEmpty(role.getMenus())) {
                List<Long> menus = StringUtil.splitLong(role.getMenus(), ",");
                List<SysRoleMeun> list = new ArrayList<>();
                SysRoleMeun roleMeun = null;
                for (Long menuId : menus) {
                    roleMeun = new SysRoleMeun();
                    roleMeun.setMenuId(menuId);
                    roleMeun.setRoleId(role.getId());
                    list.add(roleMeun);
                }
                roleMeunService.insertBatch(list);
            }
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error();
        }
    }

    @PostMapping("/update")
    public Object updateRole(HttpSession session, SysRole role) {
        Long userId = SessionHelper.getUserId(session);
        Long companyId = SessionHelper.getCompanyId(session);

        try {
            if (null == role) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }

            if (null == role.getCompanyId()) {
                role.setCompanyId(companyId);
            }

            role.setUpdateTime(new Date());
            role.setOperationId(userId);
            roleService.insertOrUpdate(role);

            if (!StringUtil.isEmpty(role.getMenus())) {
                roleMeunService.deleteByMap(MapBuilder.newMap(1).setParam("role_id", role.getId()).ok());
                List<Long> menus = StringUtil.splitLong(role.getMenus(), ",");
                List<SysRoleMeun> list = new ArrayList<>();
                SysRoleMeun roleMeun = null;
                for (Long menuId : menus) {
                    roleMeun = new SysRoleMeun();
                    roleMeun.setMenuId(menuId);
                    roleMeun.setRoleId(role.getId());
                    list.add(roleMeun);
                }
                roleMeunService.insertBatch(list);
            }
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error();
        }
    }

    @GetMapping("/selectRoleById/{id}")
    public Object selectRoleById(@PathVariable("id") Long id) {
        SysRole sysRole = roleService.selectById(id);
        return MessageResult.success(sysRole);
    }

    @PostMapping("/delete")
    public Object delRolByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        if (0 == idList.size()) {
            return MessageResult.error(PromptInfo.ERROR_DELETE_NOT_SELECT);
        }

        Integer count = userRoleService.selectByRoleIds(idList);
        if (null != count && count.compareTo(0) > 0) {
            return MessageResult.error(PromptInfo.ROLE_EXIST_USER);
        }
        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();

        for (Long id : idList) {
            map.put("id", id);
            roleService.delRoleById(map);
        }
        //// userRoleService.deleteByRoleIds(idList);
        return MessageResult.success();
    }

    /**
     * @param session
     * @param code
     * @param name
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public Object selectRoleAll(HttpSession session, @RequestParam(value = "code", defaultValue = "") String code,
                                @RequestParam(value = "name", defaultValue = "") String name,
                                @RequestParam(value = "companyId", defaultValue = "") Long companyId,
                                @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                                @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Long cid = SessionHelper.getCompanyId(session);
        if (null == cid || cid.compareTo(1L) != 0) {
            companyId = cid;
        }
        Page<SysRole> pageInfo = new Page<>(page, limit);
        Map<String, Object> params = MapBuilder.newMap(3).setParam("code", code).setParam("companyId", companyId).ok();
        if (null != name && !"".equals(name)) {
            params.put("name", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(name) + "%");
        }
        Page<JSONObject> result = roleService.selectRoleList(pageInfo, params);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    @GetMapping("/getRoleMap")
    public Object getRoleMap(HttpSession session) {
        Long companyId = SessionHelper.getCompanyId(session);
        if (null != companyId && companyId.compareTo(1L) == 0) {
            companyId = 0L;
        }
        List<JSONObject> list = roleService.getRoleMap(companyId);
        return MessageResult.success(list);
    }

}
